﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using ChuanYe.Core.Utils;
using ChuanYe.Utils;
using ChuanYe.WorkLogManagement.Api.Models;
using ChuanYe.WorkLogManagement.BLL;
using ChuanYe.WorkLogManagement.EF.SqlServer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;

namespace ChuanYe.WorkLogManagement.Api.Controllers
{
    /// <summary>
    /// 工作日志接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WorkController : ControllerBase
    {

        /// <summary>
        /// Excel 存放位置
        /// </summary>
        public readonly string EXCEL_PATH = AppDomain.CurrentDomain.BaseDirectory + "Excel";

        /// <summary>
        ///  根据用户获取其下的工作日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> Get(GetRequest obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                var list = WorkInfoBLL.Instance.Get(obj.FromUserID,obj.ToUserID,obj.StartTime,obj.EndTime,obj.FinshState,obj.Level);
                result.FirstParam = list;
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/GetWork Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }

        /// <summary>
        ///  多条日志写入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultDtoBase AddMultiple(WorkInfoMultipleRequest obj)
        {
            ResultDtoBase result = new ResultDtoBase();
            try
            {
                var infos = new List<WorkInfo>();
                foreach (var item in obj.List)
                {
                    var date = item.AddTime.HasValue ? item.AddTime.Value : DateTime.Now;
                    WorkInfo info = new WorkInfo() {
                         AddTime= date,
                         Day= date.Day,
                         Month=date.Month,
                         GUID=System.Guid.NewGuid().ToString(),
                         FinshState=item.FinshState,
                         FinshContent = item.FinshContent,
                         WorkContent=item.WorkContent,
                         IsPrivate=item.IsPrivate,
                         UserID=item.UserID,
                         Level=item.Level,
                         Remark=item.Remark,
                         RowNumber=item.RowNumber,
                    };
                    infos.Add(info);
                }
                WorkInfoBLL.Instance.Add(infos);
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/AddMultipleWork Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }

        /// <summary>
        ///  增加或者编辑
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> AddOrUpdate(WorkInfoRequest obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                var date = obj.AddTime.HasValue ? obj.AddTime.Value : DateTime.Now;
                WorkInfo info = new WorkInfo()
                {
                    AddTime = date,
                    Day = date.Day,
                    Month = date.Month,
                    GUID = obj.GUID,
                    FinshState = obj.FinshState,
                    FinshContent = obj.FinshContent,
                    WorkContent = obj.WorkContent,
                    IsPrivate = obj.IsPrivate,
                    UserID = obj.UserID,
                    Level = obj.Level,
                    Remark = obj.Remark,
                    RowNumber = obj.RowNumber,
                };
                var guid= WorkInfoBLL.Instance.AddOrUpdate(info);
                if (string.IsNullOrEmpty(guid))
                {
                    result.FirstParam = null;
                    result.Status = 0;
                    result.Message = "Update Target GUID Not Exist";
                }
                else
                {
                    result.FirstParam = guid;
                    result.Status = 1;
                    result.Message = "Requst Is Success";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/AddOrUpdate Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }

        /// <summary>
        ///  移除单条日志信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultDtoBase Remove(DelWorkInfo obj)
        {
            ResultDtoBase result = new ResultDtoBase();
            try
            {
                var delRow=WorkInfoBLL.Instance.Remove(obj.GUID);
                if (delRow == 0)
                {
                    result.Status = 0;
                    result.Message = "Update Target GUID Not Exist";
                }
                else
                {
                    result.Status = 1;
                    result.Message = "Requst Is Success";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/Remove Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 查询所有子用户(分组)工作日志 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetWorkToSelfAndChild(WorkGroupUserRequest obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                var list = WorkInfoBLL.Instance.GetWorkToSelfAndChild(obj.UserID,obj.Keyword,obj.StartTime, obj.EndTime);
                result.FirstParam = list;
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/GetWorkToSelfAndChild Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }


        /// <summary>
        /// 获取未来3天的工作日志  命名错误 待删除
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetNet3DaysWork(DelUserRequest obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                var list = WorkInfoBLL.Instance.GetNext3DaysWork(obj.UserID);
                result.FirstParam = list;
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/GetNext3DaysWork Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }



        /// <summary>
        /// 获取未来3天的工作日志
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetNext3DaysWork(DelUserRequest obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                var list = WorkInfoBLL.Instance.GetNext3DaysWork(obj.UserID);
                result.FirstParam = list;
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/GetNext3DaysWork Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }


        /// <summary>
        ///   获取 基础数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetBasicDropDownList()
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                result.FirstParam=WorkInfoBLL.Instance.GetBasicDropDownList();
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/GetBasicDropDownListInfo Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Export(ExportRequest obj)
        {
            string workPath = EXCEL_PATH;
            var browser = String.Empty;
            if (!Directory.Exists(workPath))
            {
                Directory.CreateDirectory(workPath);
            }
            var info = UserInfoBLL.Instance.Get(obj.ToUserID, null, null);
            if (info != null)
            {
                var list = WorkInfoBLL.Instance.Get(obj.FromUserID, obj.ToUserID, obj.StartTime, obj.EndTime);
                var startTime = obj.StartTime.Value;
                var endTime = obj.EndTime.Value;
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                var filePath = EXCEL_PATH +"/"+ fileName;
                using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    NPOI.SS.UserModel.IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();

                    //字体加粗
                    var font = workbook.CreateFont();
                    font.Boldweight = (short)FontBoldWeight.Bold;

                    //单元格字体居中加粗
                    var cellstyleTitle = workbook.CreateCellStyle();
                    cellstyleTitle.VerticalAlignment = VerticalAlignment.Center;
                    cellstyleTitle.Alignment = HorizontalAlignment.Center;
                    cellstyleTitle.SetFont(font);

                    //单元格字体默认加粗
                    var cellstyleTitle2 = workbook.CreateCellStyle();
                    cellstyleTitle2.SetFont(font);

                    //单元格 黄色底色 黑色字体
                    var cellstyleDay = workbook.CreateCellStyle();
                    cellstyleDay.VerticalAlignment = VerticalAlignment.Center;
                    cellstyleDay.Alignment = HorizontalAlignment.Center;
                    cellstyleDay.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index;
                    cellstyleDay.FillPattern = FillPattern.SolidForeground;
                    cellstyleDay.SetFont(font);


                    //红色字体 加粗
                    var redFont = workbook.CreateFont();
                    redFont.Color = HSSFColor.Red.Index;
                    redFont.Boldweight = (short)FontBoldWeight.Bold;

                    //底色 加粗
                    var greenFont = workbook.CreateFont();
                    greenFont.Color = HSSFColor.Green.Index;
                    greenFont.Boldweight = (short)FontBoldWeight.Bold;


                    //单元格字体居中加粗加红
                    var cellstyleTitle3 = workbook.CreateCellStyle();
                    cellstyleTitle3.VerticalAlignment = VerticalAlignment.Center;
                    cellstyleTitle3.Alignment = HorizontalAlignment.Center;
                    cellstyleTitle3.SetFont(redFont);

                    //单元格字体 居中加粗 边框
                    var cellstyleTitle4 = workbook.CreateCellStyle();
                    cellstyleTitle4.VerticalAlignment = VerticalAlignment.Center;
                    cellstyleTitle4.Alignment = HorizontalAlignment.Center;
                    cellstyleTitle4.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellstyleTitle4.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellstyleTitle4.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellstyleTitle4.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellstyleTitle4.SetFont(font);

                    //单元格字体 居中加粗 边框
                    var cellstyleTitle5 = workbook.CreateCellStyle();
                    cellstyleTitle5.VerticalAlignment = VerticalAlignment.Center;
                    cellstyleTitle5.Alignment = HorizontalAlignment.Center;
                    cellstyleTitle5.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellstyleTitle5.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellstyleTitle5.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellstyleTitle5.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;

                    var levelList = WorkInfoBLL.Instance.GetLevelList();
                    while (endTime.Month >= startTime.Month)
                    {
                        var rowIndex = 0;
                        NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(startTime.Month + "月");

                        #region 标题

                        IRow row = sheet.CreateRow(rowIndex);
                        row.Height = 30 * 10;
                        ICell cellTitle = row.CreateCell(0);
                        cellTitle.SetCellValue("工  作  日  志");
                        cellTitle.CellStyle = cellstyleTitle;
                        sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4));
                        sheet.SetColumnWidth(1, 60 * 256);
                        sheet.SetColumnWidth(3, 30 * 256);
                        sheet.SetColumnWidth(4, 20 * 256);
                        sheet.AutoSizeColumn(0);
                        rowIndex++;
                        #endregion

                        //月的第一天与最后一天
                        var firstDay = SundryHelper.FirstDayOfMonth(startTime).Day;
                        var lastDay = SundryHelper.LastDayOfMonth(startTime).Day;
                        for (int i = firstDay; i <=lastDay; i++)
                        {
                            #region 每日抬头
                            var date = DateTime.Parse(startTime.Year+"-"+startTime.Month+"-"+i+" 00:00:00" );
                            //公历节日 
                            var holiday = ChinaDate.GetHoliday(date);
                            //农历节日
                            var chineseHoliday = ChinaDate.GetChinaHoliday(date);
                            //天干地支年名
                            var chineseYear = ChinaDate.GetYear(date, 1);
                            //农历月份
                            var chineseMonth = ChinaDate.GetMonth(date);
                            //农历日期
                            var chineseDay = ChinaDate.GetDay(date);
                            //星期几(中文)


                            var chineseWeek = ChinaDate.GetChinaWeek(date);
                            IRow dayRow = sheet.CreateRow(rowIndex);
                            row.Height = 30 * 10;

                            ICell c1 = dayRow.CreateCell(0);
                            c1.SetCellValue(i+"日");
                            c1.CellStyle = cellstyleDay;


                            ICell c2 = dayRow.CreateCell(1);
                            c2.SetCellValue(chineseYear+ chineseMonth+ chineseDay);
                            c2.CellStyle = cellstyleTitle2;


                            ICell c3 = dayRow.CreateCell(2);
                            c3.SetCellValue(chineseWeek);
                            if (chineseWeek == "星期六" || chineseWeek == "星期日")
                            {
                                c3.CellStyle = cellstyleTitle3;
                            }
                            else
                            {
                                c3.CellStyle = cellstyleTitle;
                            }

                            ICell c4 = dayRow.CreateCell(3);
                            c4.SetCellValue(holiday+chineseHoliday);
                            c4.CellStyle = cellstyleTitle3;

                            ICell c5 = dayRow.CreateCell(4);
                            c5.SetCellValue("");
                            rowIndex++;
                            #endregion

                            #region 每日标题
                            IRow dayTitleRow = sheet.CreateRow(rowIndex);
                            ICell c11 = dayTitleRow.CreateCell(0);
                            c11.SetCellValue("");
                            c11.CellStyle = cellstyleTitle4;

                            ICell c22 = dayTitleRow.CreateCell(1);
                            c22.SetCellValue("工  作  内  容");
                            c22.CellStyle = cellstyleTitle4;

                            ICell c33 = dayTitleRow.CreateCell(2);
                            c33.SetCellValue("重要性");
                            c33.CellStyle = cellstyleTitle4;

                            ICell c44 = dayTitleRow.CreateCell(3);
                            c44.SetCellValue("完成情况");
                            c44.CellStyle = cellstyleTitle4;

                            ICell c55 = dayTitleRow.CreateCell(4);
                            c55.SetCellValue("备注");
                            c55.CellStyle = cellstyleTitle4;
                            rowIndex++;
                            #endregion

                            #region 日历数据
                            var tempEndDate = date.AddHours(23).AddMinutes(59).AddSeconds(59);
                            var data = list.Where(p => p.AddTime >= date && p.AddTime <= tempEndDate).OrderBy(o=>o.AddTime).ToList();
                            int rowNumber = 1;
                            foreach (var item in data)
                            {
                                IRow tempRow = sheet.CreateRow(rowIndex);
                                ICell c111 = tempRow.CreateCell(0);
                                c111.SetCellValue(rowNumber);
                                c111.CellStyle = cellstyleTitle4;
                                c111.CellStyle = cellstyleTitle4;
                                ICell c222 = tempRow.CreateCell(1);
                                c222.SetCellValue(item.WorkContent);
                                c222.CellStyle = cellstyleTitle5;

                                ICell c333 = tempRow.CreateCell(2);
                                var levelInfo=levelList.Where(p => item.Level == p.Level).FirstOrDefault();
                                c333.SetCellValue(levelInfo==null?string.Empty:levelInfo.Name);
                                c333.CellStyle = cellstyleTitle5;

                                ICell c444 = tempRow.CreateCell(3);
                                c444.SetCellValue(item.FinshContent);
                                c444.CellStyle = cellstyleTitle5;

                                ICell c555 = tempRow.CreateCell(4);
                                c555.SetCellValue(item.Remark);
                                c555.CellStyle = cellstyleTitle5;

                                rowNumber++;
                                rowIndex++;
                            }

                            if (data.Count < 10)
                            {
                                while (rowNumber < 11)
                                {
                                    IRow tempRow = sheet.CreateRow(rowIndex);
                                    ICell c111 = tempRow.CreateCell(0);
                                    c111.SetCellValue(rowNumber);
                                    c111.CellStyle = cellstyleTitle4;

                                    ICell c222 = tempRow.CreateCell(1);
                                    c222.SetCellValue("");
                                    c222.CellStyle = cellstyleTitle5;

                                    ICell c333 = tempRow.CreateCell(2);
                                    c333.SetCellValue("");
                                    c333.CellStyle = cellstyleTitle5;

                                    ICell c444 = tempRow.CreateCell(3);
                                    c444.SetCellValue("");
                                    c444.CellStyle = cellstyleTitle5;

                                    ICell c555 = tempRow.CreateCell(4);
                                    c555.SetCellValue("");
                                    c555.CellStyle = cellstyleTitle5;
                                    rowNumber++;
                                    rowIndex++;
                                }
                            }
                            #endregion
                        }

                        startTime = startTime.AddMonths(1);
                    }
                    workbook.Write(fs);
                    fs.Close();
                }
                return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", info.RealName+"工作日志.xls");
            }
            else
            {
                return NotFound();
            }
        }


        /// <summary>
        /// 日志统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> Statistics(GetRequest obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                result.FirstParam = WorkInfoBLL.Instance.Statistics(obj.StartTime,obj.EndTime,obj.FinshState,obj.Level,obj.ToUserID);
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/Statistics Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }


        /// <summary>
        ///  用户填写状态及数量
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetEveryDayWriteStatus(WriteStatusRequest obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                result.FirstParam = WorkInfoBLL.Instance.GetEveryDayWriteStatus(obj.StartTime, obj.EndTime, obj.UserID);
                result.Status = 1;
                result.Message = "Requst Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Work/Statistics Server Error";
                LogHelper.Error(ex.Message);
            }
            return result;
        }
    }
}